#include "Rock.h"
#include "RockFall.h"

void Rock::update(float frameTime)
{
	particle.update(frameTime);

	/** Check Level contact */
#pragma region LEVELCOLLISION
	Level* level = LevelManager::getCurrentLevel();
	D3DXVECTOR3 movement = particle.position - position;
	D3DSURFACE_DESC rockDesc;
	texture->GetLevelDesc(0, &rockDesc);
	D3DXVECTOR3 size((float)rockDesc.Width, (float)rockDesc.Height, 0);
	BoundingBox bounds = { position, size };
	position = level->checkCollision(this, bounds, movement);

	if (D3DXVec3Length(&(position - particle.position)) > 0.1f)
	{
		D3DXVECTOR3 contactNormal = position - particle.position;
		D3DXVec3Normalize(&contactNormal, &contactNormal);
		Particle contactParticle(particle.position, D3DXVECTOR3(0, 0, 0), 1000.0f);
		Particle* particles[2] = { &particle, &contactParticle };
		Contact contact(particles, 1.0f, contactNormal);
		contact.resolve(frameTime);
	}
	particle.position = position;
#pragma endregion

	/** Check collision with enemies */
#pragma region ENEMIES
	std::list<Entity*>* enemies = EntityManager::getNamedEntities("Enemy");
	if (enemies->size() > 0)
	{
		D3DSURFACE_DESC rockDesc;
		texture->GetLevelDesc(0, &rockDesc);
		D3DXVECTOR3 rockSize((float)rockDesc.Width, (float)rockDesc.Height, 0);
		BoundingBox rockBox = { position, rockSize };

		std::list<Entity*>::iterator iter = enemies->begin();
		for (; iter != enemies->end(); iter++)
		{
			if ((*iter)->isAlive())
			{
				D3DSURFACE_DESC enemyDesc;
				enemies->front()->getTexture()->GetLevelDesc(0, &enemyDesc);
				D3DXVECTOR3 enemySize((float)enemyDesc.Width, (float)enemyDesc.Height, 0);
				BoundingBox enemyBox = { (*iter)->getPosition(), enemySize };
				if (TestCollision(rockBox, enemyBox))
				{
					alive = false;
					Message message((*iter), "Die", 0);
					MessageHandler::sendMessage(message);
				}
			}
		}
	}
#pragma endregion
}

void Rock::draw(ID3DXSprite* sprite)
{
	D3DXVECTOR3 tempPos = position - level->getOffset();
	if (alive)
		sprite->Draw(texture, 0, 0, &tempPos, D3DCOLOR_XRGB(255, 255, 255));
}